<template>
	<a-form-item
		:class="{
			[slotClass ? slotClass : '']: true,
			'app-control-form__item': true,
			[`app-control-form__item--${labelPos.toLowerCase()}`]: true,
			[`app-control-form__item__${name}`]: true,
			[`anchor__${name}`]: enableAnchor,
		}"
		htmlFor=""
		:colon="false"
		:style="slotStyle"
		:name="name"
		:rules="rules"
		:help="error"
		:labelCol="{ style: { width: formItemLabelWidth } }"
	>
		<template #label v-if="showLabel && labelPos !== 'NONE'">
			<a-tooltip>
				<template #title v-if="showTip">
					{{ label }}
				</template>
				<div
					ref="labelElement"
					:class="{
						[labelClass ? labelClass : '']: true,
						'app-form-item__label': true,
					}"
				>
					{{ label }}
				</div>
			</a-tooltip>
		</template>
		<slot></slot>
	</a-form-item>
</template>
<script setup lang="ts">
import { formItemProps } from '../form';
import { Ref } from 'vue';
import { createUUID } from 'qx-util';

const props = defineProps(formItemProps);

const showTip = ref(false);

const labelElement: Ref<any> = ref(null);

const handleShowTip = () => {
	const element = labelElement.value;
	if (element && props.showLabel && !props.emptyCaption) {
		if (element.scrollWidth > element.offsetWidth) {
			showTip.value = true;
		} else {
			// 父级先隐藏，前面判断将失效，仿真绘制label元素获取offsetWidth和labelWidth对比
			if (
				element.scrollWidth === 0 &&
				element.offsetWidth === 0 &&
				props.label &&
				props.labelWidth
			) {
				const formItemLabel = document.createElement('span');
				const id = createUUID();
				formItemLabel.id = id;
				formItemLabel.className = 'app-form-item__label';
				formItemLabel.innerText = props.label;
				const bodyContent = document.querySelector('body');
				if (bodyContent) {
					bodyContent.appendChild(formItemLabel);
				}
				let labelWidth = props.labelWidth;
				if (!props.showLabel || props.labelPos == 'NONE') {
					labelWidth = 0;
				}
				if (formItemLabel.offsetWidth > labelWidth) {
					showTip.value = true;
				}
				const targetLabel = document.getElementById(id);
				if (targetLabel) {
					targetLabel.remove();
				}
			}
		}
	}
};

const formItemLabelWidth = computed(() => {
	let labelWidth = `${props.labelWidth ? props.labelWidth : 0}px`;
	if (!props.showLabel || props.labelPos == 'NONE') {
		labelWidth = '0px';
	}
	return labelWidth;
});

onMounted(() => {
	handleShowTip();
});
</script>
